package com.tianruan.dc.common.utils.wechat.qy;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.tianruan.dc.common.utils.HttpUtils;
import com.tianruan.dc.common.utils.JedisUtils;
import com.tianruan.dc.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author: Dong
 * @Email: dong980514280@gmail.com
 * @Create: 2022-02-17 12:58
 * @PS 企业微信服务端Api工具类
 */
@Component
public class QYServerApiUtils {

    private static final String QY_TOKEN_NAME = "wechat:qy:access_token";

    private static String corpid;
    private static String agentid;
    private static String corpsecret;
    private static String miniAppId;


    @Autowired
    private Environment env;

    @PostConstruct
    public void config() {
        corpid = env.getProperty("wx.qy.corpid");
        agentid = env.getProperty("wx.qy.agentid");
        corpsecret = env.getProperty("wx.qy.corpsecret");
        miniAppId = env.getProperty("wx.mini.appId");
    }

    // 获取令牌
    public static String getToken() {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + corpid + "&corpsecret=" + corpsecret;
        try {
            String wechatQYToken = JedisUtils.get(QY_TOKEN_NAME);
            if (StringUtils.isBlank(wechatQYToken)) {
                String response = HttpUtils.get(url);
                TokenEntity token = JSONObject.parseObject(response, TokenEntity.class);
                JedisUtils.set(QY_TOKEN_NAME, token.getAccessToken(), new Date().getTime() + token.getExpiresIn() * 1000L);
                wechatQYToken = token.getAccessToken();
            }
            return wechatQYToken;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        return null;
    }

    // 根据手机号码获取用户id
    public static String getUserIdByPhone (String phone) {
        // 判断是否是正确手机号，不是就抛出 手机号异常
        String accessToken = getToken();
        String url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserid?access_token=" + accessToken;
        String response = HttpUtils.postJson(url, "{\"mobile\": \"" + phone + "\"}");
        UserEntity userEntity = JSONObject.parseObject(response, UserEntity.class);
        if (userEntity != null && userEntity.getErrcode() == 0) {
            return userEntity.getUserid();
        }
        return null;
    }

    /**
     * 发送微信小程序消息
     * @return
     */
    public static boolean sendMessageMini (String userids, String title, String description, List<Map<String, String>> contentItem) {

        String accessToken = getToken();
        String url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + accessToken;

        MessageJson messageJson = new MessageJson();
        messageJson.setTouser(userids);
        messageJson.setAgentid(agentid);
        messageJson.setMsgtype("miniprogram_notice");
        MessageJson.MiniprogramNotice miniprogramNotice = messageJson.getMiniprogram_notice();
        miniprogramNotice.setAppid(miniAppId);
        miniprogramNotice.setPage("pages/index");
        miniprogramNotice.setTitle(title);
        miniprogramNotice.setDescription(description);
        miniprogramNotice.setEmphasis_first_item(true);
        miniprogramNotice.setContent_item(contentItem);
        messageJson.setEnable_id_trans(0);
        messageJson.setEnable_duplicate_check(0);
        messageJson.setDuplicate_check_interval(1800);

        System.out.println(JSONObject.toJSONString(messageJson));
        String response = HttpUtils.postJson(url, JSONObject.toJSONString(messageJson, SerializerFeature.WriteBigDecimalAsPlain));
        MessageResponeEntity messageResponeEntity = JSONObject.parseObject(response, MessageResponeEntity.class);
        if (messageResponeEntity != null && messageResponeEntity.getErrcode() == 0) {
            return true;
        }
        return false;
    }

}
